<template>
  <div>
    <div style="height: 40px"></div>
    <center>
      <van-image
        round
        width="8rem"
        height="8rem"
        :src=images
      />
    </center>
    <center><h2>易租车</h2></center>
    <div style="height: 70px;"></div>
    <van-form @submit="onSubmit" > <!-- -->
      <van-field
        v-model="username"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="codeNum"
        name="codeNum"
        label="验证码"
        placeholder="请输入验证码"
        center
        clearable
      >
        <template #button>
          <van-image
            width="5rem"
            height="5rem"
            fit="contain"
            :src="verCode"
            @click="getVerCode"
          />
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
  import Vue from 'vue';
  import request from '@/utils/request'
  import { Form } from 'vant';
  import { Field } from 'vant';
  import { Image as VanImage } from 'vant';
  import { Toast } from 'vant';

  Vue.use(Toast);
  Vue.use(VanImage);
  Vue.use(Field);
  Vue.use(Form);

  export default {
    name: "Login",
    data() {
      return {
        username: '',
        password: '',
        images: require('@/assets/mylogo/logo3.png'),
        verCode: '',  //验证码的base64字符串
        codeId:'', //后端传来的验证码id
        codeNum:'' //用户输入的验证码
      };
    },
    created() {
      //获取验证码
      this.getVerCode();

    },
    methods: {
      onSubmit(values) {
        let that = this;
        request({
          url: '/customer/login',
          method: 'post',
          data:{
            "phoneNum":this.username,
            "password":this.password,
            "codeNum": this.codeNum,
            "codeId": this.codeId
          }
        }).then(res => {
          if(res.code != 200){
            const message = res.message;
            Toast(message);
            return;
          }
          let data = res.data;
          console.log(data)
          localStorage.setItem("token",data);
          Toast('登录成功，即将自动跳转');
          setTimeout(function (){
            that.$router.push('/')
          }, 1000);
        });
      },
      getVerCode(){
        request({
          url: '/code/createcode',
          method: 'post'
        }).then(res => {
          this.verCode = res.verCode;
          this.codeId = res.codeId;
        });
      }
    },
  };
</script>

<style scoped>

</style>
